package org.zjut.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.zjut.bean.Leaner;
import org.zjut.db.AccountDataBase;
import org.zjut.util.CommonUtil;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 账户相关操作控制器
 * Created by Rising on 17/7/9.
 */
@Controller
public class AccountController {
    @Autowired
    AccountDataBase accountDataBase;

    /**
     * 测试
     * @return
     */
    @RequestMapping(value="/index", method = RequestMethod.GET)
    @ResponseBody
    public String index(){
        Map<String,Object> result = new HashMap();
        Leaner leaner = new Leaner();
        leaner.setId(UUID.randomUUID().toString());
        leaner.setName("rising");
        leaner.setAge(28);
        leaner.setSex("male");
        result.put("success",true);
        result.put("message",leaner);
        return "callback("+JSON.toJSONString(result)+")";
    }


    /**
     * 登录服务
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/login", method = RequestMethod.POST,produces="application/json;charset=utf-8")
    public String login(HttpServletRequest request){
        JSONObject params = JSON.parseObject(getBodyRequest(request));
        if(request==null){
            return JSON.toJSONString(CommonUtil.setErrorInfo("请求参数有问题，请注意检查"));
        }

        return JSON.toJSONString(accountDataBase.login(params));
    }

    /**
     * 获取用户信息
     * @param request
     * @return
     */
    @RequestMapping(value="/getAccount", method = RequestMethod.POST,produces = "application/json;charset=utf-8")
    @ResponseBody
    public String getAccount(HttpServletRequest request){
        JSONObject params = JSON.parseObject(getBodyRequest(request));
        if(request==null){
            return JSON.toJSONString(CommonUtil.setErrorInfo("请求参数有问题，请注意检查"));
        }
        return JSON.toJSONString(accountDataBase.getAccount(params));
    }

    /**
     *  插入用户账户
     * @param request
     * @return
     */
    @RequestMapping(value="/addAccount", method = RequestMethod.POST,produces = "application/json;charset=utf-8")
    @ResponseBody
    public String addAccount(HttpServletRequest request){
        JSONObject params = JSON.parseObject(getBodyRequest(request));
        if(request==null){
            return JSON.toJSONString(CommonUtil.setErrorInfo("请求参数有问题，请注意检查"));
        }
        try{
            return JSON.toJSONString(accountDataBase.insertUserAccount(params));
        }catch (Exception e){
            return JSON.toJSONString(CommonUtil.setErrorInfo("插入失败"));
        }
    }


    /**
     * 修改用户信息
     * @param request
     * @return
     */
    @RequestMapping(value="/editAccount", method = RequestMethod.POST,produces = "application/json;charset=utf-8")
    @ResponseBody
    public String editAccount(HttpServletRequest request){
        if(request==null){
            return JSON.toJSONString(CommonUtil.setErrorInfo("请求参数有问题，请注意检查"));
        }
        try{
            JSONObject params = JSON.parseObject(getBodyRequest(request));
            return JSON.toJSONString(accountDataBase.editAccount(params));
        }catch (Exception e){
            return JSON.toJSONString(CommonUtil.setErrorInfo("修改失败"));
        }
    }

    /**
     * 删除用户信息
     * @param userCode
     * @return
     */
    @RequestMapping(value="/delAccount/{userCode}", method = RequestMethod.POST,produces = "application/json;charset=utf-8")
    @ResponseBody
    public String delAccount (@PathVariable String userCode){
        if(userCode == null || userCode.isEmpty()){
            return JSON.toJSONString(CommonUtil.setErrorInfo("请求参数有问题，请注意检查"));
        }
        return JSON.toJSONString(accountDataBase.delAccount(userCode));
    }

    /**
     * JS 跨域请求格式封装
     * @param json
     * @return
     */
    public String jsonCallback(String json){
        return "callback("+json+")";
    }

    //获取客户端请求的JSON数据
    public String getBodyRequest(HttpServletRequest request) {
        // 把reqeust的body读取到StringBuilder
        BufferedReader reader = null;
        try {
            reader = request.getReader();
        } catch (IOException e) {
            e.printStackTrace();
        }
        StringBuilder sb = new StringBuilder();

        char[] buf = new char[1024];
        int rd;
        try {
            while ((rd = reader.read(buf)) != -1) {
                sb.append(buf, 0, rd);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
//        System.out.println(sb.toString());
        return sb.toString();
    }



}
